<template>
  <a-menu mode="inline">
    <a-menu-item-group v-for="menuGroup in menuData" :key="menuGroup.path">
      <span slot="title">{{ menuGroup.name }}</span>
      <a-menu-item v-for="(menuItem, index) in menuGroup" :key="index"></a-menu-item>
    </a-menu-item-group>
  </a-menu>
</template>
<script>
export default {
  name: 'IMenu',
  props: {
    menuData: {
      type: Array,
      required: true
    },
    theme: {
      type: String,
      required: false,
      default: 'dark'
    },
    mode: {
      type: String,
      required: false,
      default: 'inline'
    },
    collapsed: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data() {
    return {
      openKeys: [],
      selectedKeys: [],
      cachedOpenKeys: []
    };
  },
  computed: {
    rootSubmenuKeys() {
      let keys = [];
      this.menuData.forEach(item => {
        keys.push(item.path);
      });
      return keys;
    }
  },
  created() {
    this.updateMenu();
  },
  watch: {
    collapsed(val) {
      if (val) {
        this.cachedOpenKeys = this.openKeys;
        this.openKeys = [];
      } else {
        this.openKeys = this.cachedOpenKeys;
      }
    },
    $route: function() {
      this.updateMenu();
    }
  },
  methods: {
    onOpenChange(openKeys) {
      const latestOpenKey = openKeys.find(key => this.openKeys.indexOf(key) === -1);
      if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
        this.openKeys = openKeys;
      } else {
        this.openKeys = latestOpenKey ? [latestOpenKey] : [];
      }
    },
    updateMenu() {
      let routes = this.$route.matched.concat();
      if (routes.length >= 4 && this.$route.meta.hidden) {
        routes.pop();
        this.selectedKeys = [routes[2].path];
      } else {
        this.selectedKeys = [routes.pop().path];
      }

      let openKeys = [];
      if (this.mode === 'inline') {
        routes.forEach(item => {
          openKeys.push(item.path);
        });
      }

      this.collapsed ? (this.cachedOpenKeys = openKeys) : (this.openKeys = openKeys);
    }
  }
};
</script>
